package com.leessy.r229

import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.PixelFormat
import android.os.IBinder
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ProgressBar
import android.widget.TextView
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.TimeUtils
import com.leessy.r229.config.Config
import com.leessy.r229.constants.Constants
import com.leessy.r229.server.http.LoadTask
import com.leessy.r229.utils.AppUtil
import com.leessy.r229.utils.BoardWatchUtils
import com.leessy.r229.utils.DevicesUtil
import com.leessy.r229.utils.LogWatcher
import com.leessy.r229.utils.OtaUtil
import com.leessy.r229.utils.PhoneUtil

class MService : Service() {
    override fun onBind(arg0: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand: ---- intent===00=== $intent")
        if (intent == null) {
            return START_NOT_STICKY
        }
//        Log.d(TAG, "onStartCommand() intent = $intent, flags = $flags, startId = $startId")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "onCreate() --------- ")
        mService = this
        initFloatWindow()
        checkConfig()

        AppUtil.initConfig()
        OtaUtil.initFile()
        PhoneUtil.firstInitIMEI()
        registernetword()
        LoadTask.startTask()
        DevicesUtil.setDeviceLog(Config.systemlog)
        LogWatcher.getInstance().init(applicationContext).startWatch()

//        showFloatWindow("1111111")
//        showDownloader(20)
        AppUtil.startApp(Config.autoRunApp!!)
    }

    val networkChangeReceiver = NetBroadcastReceiver()

    /*Register the broadcast receiver to receive the broadcast of CONNECTIVITY CHANGE*/
    private fun registernetword() {
        registerReceiver(networkChangeReceiver, IntentFilter().apply {
            addAction("android.net.conn.CONNECTIVITY_CHANGE")
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(networkChangeReceiver)
    }


    lateinit var mWindowManager: WindowManager
    lateinit var rootLayout: View
    lateinit var mWindowParams: WindowManager.LayoutParams
    private fun initFloatWindow() {
        rootLayout = LayoutInflater.from(this)
            .inflate(R.layout.floatingwidow_in_activity, null)
//        rootLayout?.setOnTouchListener(this)
        mWindowParams = WindowManager.LayoutParams()
        mWindowManager = App.app.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mWindowParams.type = WindowManager.LayoutParams.TYPE_PHONE
        mWindowParams.format = PixelFormat.RGBA_8888
        // 设置悬浮窗不获取焦点的原因就是为了传递事件
        mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL

        mWindowParams.gravity = Gravity.START or Gravity.TOP
        mWindowParams.height = 90// WindowManager.LayoutParams.MATCH_PARENT
        mWindowParams.width = WindowManager.LayoutParams.MATCH_PARENT
//        val metrics = DisplayMetrics()
//        // 默认固定位置，靠屏幕左边缘的中间
//        mWindowManager.defaultDisplay.getMetrics(metrics)
//        mWindowParams.x = 0
//        mWindowParams.y = metrics.heightPixels/2
    }


    var downlodaerView: View? = null
    var isShowDownLoader = false

    fun showDownloader(int: Int, type: Int = 0) {
        ThreadUtils.runOnUiThread(Runnable {
            if (downlodaerView == null) {
                downlodaerView =
                    LayoutInflater.from(this).inflate(R.layout.floatingwidow_downloader, null)
                var mWindowParams = WindowManager.LayoutParams()
                mWindowManager = App.app.getSystemService(Context.WINDOW_SERVICE) as WindowManager
                mWindowParams.type = WindowManager.LayoutParams.TYPE_PHONE
                mWindowParams.format = PixelFormat.RGBA_8888
                // 设置悬浮窗不获取焦点的原因就是为了传递事件
                mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                        WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                mWindowParams.gravity = Gravity.CENTER
                mWindowParams.height =
                    WindowManager.LayoutParams.WRAP_CONTENT// WindowManager.LayoutParams.MATCH_PARENT
                mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT
                mWindowManager.addView(downlodaerView, mWindowParams)
                isShowDownLoader = true
            } else {
                downlodaerView?.findViewById<ProgressBar>(R.id.progress)?.progress = int
                downlodaerView?.findViewById<TextView>(R.id.progressText)?.text = "$int%"
            }
            if (type == 2) downlodaerView?.findViewById<TextView>(R.id.title)?.text = "系统更新下载"
            if (type == 1) downlodaerView?.findViewById<TextView>(R.id.title)?.text = "App下载"
        })
    }

    fun closeDownloader() {
        ThreadUtils.runOnUiThread(Runnable {
            if (downlodaerView != null && isShowDownLoader) {
                mWindowManager.removeView(downlodaerView)
                isShowDownLoader = false
                downlodaerView = null
            }
        })
    }

    var hideall = false
    fun checkConfig() {
        ThreadUtils.runOnUiThread(Runnable {
//            if (Config.deviceLock || isAutoLock()) {
            println("=checkConfig=deviceLockAction=${Constants.deviceLockAction}==deviceLockText=${Constants.deviceLockText}==thread==${Thread.currentThread().name}")
            if (Constants.deviceLockAction == 2) {//不再检测日期超时自动锁定的
                if (Constants.deviceLockText.isNullOrBlank()) {
                    showFloatWindow("设备已锁定")
                } else {
                    //                    showFloatWindow(Config.deviceLockMsg)
                    showFloatWindow(Constants.deviceLockText)
                }
                hideall = true
                BoardWatchUtils.closeWatchdog()
                //禁用所有后装APP
                for (s in AppUtil.getAllUserPkg()) {
                    AppUtil.hideApp(s)
                }
//            } else if (Config.deviceExpire && aboutToExpire()) {
            } else if (Constants.deviceLockAction == 1) {//不再检测超时自动锁定的日期
//                showFloatWindow(Config.deviceExpireMsg)
                if (Constants.deviceLockText.isNullOrBlank()) {
                    showFloatWindow("设备预警")
                } else {
                    //                    showFloatWindow(Config.deviceLockMsg)
                    showFloatWindow(Constants.deviceLockText)
                }
                if (hideall) {
                    hideall = false
                    AppUtil.resetHideApp()
                }
            } else {
                remove()
                if (hideall) {
                    hideall = false
                    AppUtil.resetHideApp()
                }
            }
        })
    }


    var isShowFloat = false
    private fun showFloatWindow(text: String?) {
        rootLayout?.findViewById<TextView>(R.id.tv)?.setText("$text")
        if (null == rootLayout?.parent) {
            mWindowManager?.addView(rootLayout, mWindowParams)
            isShowFloat = true
        }
    }

    private fun remove() {
        if (null != rootLayout.parent) {
            mWindowManager.removeView(rootLayout)
            isShowFloat = false
        }
    }

    fun aboutToExpire(): Boolean {
        Log.e(TAG,"=aboutToExpire=${Config.deviceAutoLockDate}")
        if (Config.deviceAutoLockDate!!.length != 8) return false
        val string2Millis = TimeUtils.string2Millis(Config.deviceAutoLockDate, "yyyyMMdd")
        val dayMillis = 24 * 60 * 60 * 1000
        val configDeviceExpireDay = Config.deviceExpireDay.toLong() * dayMillis
        Log.e(TAG, "aboutToExpire:  $string2Millis    deviceExpireDay=${Config.deviceExpireDay}=currentTimeMillis=${System.currentTimeMillis()}==dayMillis==${dayMillis}==configDeviceExpireDay=${configDeviceExpireDay}")
        if (string2Millis > 0 && (string2Millis - System.currentTimeMillis()) <= configDeviceExpireDay)
            return true
        else return false
    }

    fun isAutoLock(): Boolean {
        if (Config.deviceAutoLockDate!!.length != 8) return false
        val string2Millis = TimeUtils.string2Millis(Config.deviceAutoLockDate, "yyyyMMdd")
        if (string2Millis > 0 && System.currentTimeMillis() > string2Millis) return true
        else return false
    }

    companion object {
        var mService: MService? = null
//        fun updateConfig(data: ConfigData) {
//            Config.deviceExpire = data.deviceExpire
//            Config.deviceExpireMsg = data.deviceExpireMsg
//            if (Config.deviceExpire) {
//                mService?.showFloatWindow(Config.deviceExpireMsg)
//            } else {
//                mService?.remove()
//            }
//        }

        private const val TAG = "MService"
    }

}
